package com.cl.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cl.annotation.IgnoreAuth;
import com.cl.entity.ConfigEntity;
import com.cl.entity.EIException;
import com.cl.service.ConfigService;
import com.cl.utils.R;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("file")
@SuppressWarnings({"unchecked", "rawtypes"})
public class FileController {

    @Autowired
    private ConfigService configService;

    // 获取上传根目录路径（推荐统一提取）
    private final String UPLOAD_DIR = System.getProperty("user.dir") + File.separator + "upload";

    /**
     * 上传文件
     */
    @IgnoreAuth
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file, String type) throws Exception {
        if (file.isEmpty()) {
            throw new EIException("上传文件不能为空");
        }

        // 确保上传目录存在
        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) uploadDir.mkdirs();

        // 生成文件名
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);
        String fileName = new Date().getTime() + "." + fileExt;

        // 保存文件
        File dest = new File(uploadDir, fileName);
        file.transferTo(dest);

        // 配置保存
        if ("1".equals(type)) {
            ConfigEntity configEntity = configService.selectOne(
                    new EntityWrapper<ConfigEntity>().eq("name", "faceFile")
            );
            if (configEntity == null) {
                configEntity = new ConfigEntity();
                configEntity.setName("faceFile");
            }
            configEntity.setValue(fileName);
            configService.insertOrUpdate(configEntity);
        }

        return R.ok().put("file", fileName).put("url", "/upload/" + fileName);
    }

    /**
     * 下载文件
     */
    @IgnoreAuth
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam String fileName) {
        try {
            File file = new File(UPLOAD_DIR, fileName);
            if (!file.exists()) {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
